<template>
    <view class="m-search-bar" :class="{ 'm-search-bar-fixed': fixed }">
        <uni-search-bar
            v-model="searchValue"
            :placeholder="placeholder"
            @focus="focusFun"
            @confirm="(val:any)=>emit('confirm', val)"
            @cancel="(val:any)=>emit('cancel', val)"
            @clear="(val:any)=>emit('clear', val)"
            @input="(val:any)=>emit('update:modelValue', val)"
        ></uni-search-bar>
    </view>
</template>

<script lang="ts" setup>
import { ref, watchEffect } from 'vue'
const props = defineProps({
    placeholders: { type: Array<string>, default: [] },
    modelValue: String,
    fixed: { type: Boolean, required: false }
})

let placeholder = ref('请输入搜索内容')
initPlaceholder()
function initPlaceholder() {
    setInterval(() => {
        if (props.placeholders.length > 0) {
            placeholder.value = props.placeholders[Math.round(new Date().getTime() / 1000) % props.placeholders.length]
        }
    }, 3000)
}

const emit = defineEmits(['update:modelValue', 'focus', 'confirm', 'cancel', 'clear'])
let searchValue = ref('')
function focusFun() {
    if (props.placeholders.length > 0) {
        searchValue.value = placeholder.value
    }
    emit('update:modelValue', searchValue.value)
    emit('focus', searchValue.value)
}
watchEffect(() => {
    searchValue.value = props.modelValue || ''
})
</script>

<style lang="scss" scoped>
.m-search-bar {
    background-color: white;
}
.m-search-bar-fixed {
    position: fixed;
}
</style>
